package com.ky.leetcode.剑指Offer;

/*

定义一个函数，输入一个链表的头节点，反转该链表并输出反转后链表的头节点。

    示例:
    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL
     
    限制：
    0 <= 节点个数 <= 5000

*/

public class 剑指Offer24反转链表 {

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode headNext = new ListNode(3);
        ListNode last = new ListNode(2);
        head.next = headNext;
        headNext.next = last;
        Solution solution = new Solution();
        ListNode reverseHead = solution.reverseList(head);
        while (reverseHead != null) {
            System.out.println(reverseHead.val);
            reverseHead = reverseHead.next;
        }
    }

    static class Solution {
        public ListNode reverseList(ListNode head) {
            ListNode reverseHead = null;
            while (head != null) {
                ListNode oldReverseHead = reverseHead;
                reverseHead = new ListNode(head.val);
                reverseHead.next = oldReverseHead;
                head = head.next;
            }
            return reverseHead;
        }
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}
